<?php
require 'helper/Db.php';
require 'helper/helper.php';

$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);
$email = htmlentities($data['email']);
$captcha = htmlentities($data['captcha']);
$captcha = rsaDecrypt($captcha);

//验证格式
if(empty($email) || empty($captcha)) {
    jsonReturn(['code' => 1, 'msg' => '参数不全']);
}
$pattern = "/^\S+@\S+\.\S+$/";
if (!preg_match($pattern, $email)) {
    jsonReturn(['code' => 1, 'msg' => '邮箱格式不正确']);
}
if (strlen(trim($captcha)) != 6) {
    jsonReturn(['code' => 1, 'msg' => '验证码不足6位']);
}

//验证验证码是否符合
$db = new Db();
$min5before = date('Y-m-d H:i:s', time() - 300);
$query = "select * from captchas where email = :email and captcha = :captcha and add_time > :min5";
$result = $db->query1($query, [':email' => ['data' => $email], ':captcha' => ['data' => $captcha], ':min5' => ['data' => $min5before]]);
if ($result) {
    //验证通过删除验证码
    $query = "delete from captchas where email = :email";
    $db->execute($query, [':email' => $email]);
    //更新用户激活状态
    $query = "update users set enable = 1 where email = :email";
    $db->execute($query, [':email' => $email]);
    jsonReturn(['code' => 0, 'msg' => '验证码匹配']);
} else {
    jsonReturn(['code' => 1, 'msg' => '验证码不匹配']);
}